package org.zero.onlinesubject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.zero.onlinesubject.common.constant.RedisConstant;
import org.zero.onlinesubject.common.vo.*;
import org.zero.onlinesubject.entity.*;
import org.zero.onlinesubject.mapper.ChapterMapper;
import org.zero.onlinesubject.mapper.UserMapper;
import org.zero.onlinesubject.service.*;
import org.zero.onlinesubject.service.impl.LiveRoomServiceImpl;
import org.zero.onlinesubject.utils.IDWorker;
import org.zero.onlinesubject.utils.UserContextHolder;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

@RestController
@RequestMapping("/course/api")
public class CourseController {

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CourseService courseService;

    @Resource
    private ChapterService chapterService;

    @Resource
    private SystemFileService fileService;

    @Resource
    private TagTypeService tagTypeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private LiveRoomService liveRoomService;

    @GetMapping("/getBizId")
    public Result<String> createBizID(){
        return Result.ok(IDWorker.createCID());
    }

    @GetMapping("/getVideoID")
    public Result<String> createVideoID(){
        return Result.ok(IDWorker.createVideoID());
    }

    // 获取课程类型列表
    @GetMapping("/courseTypeList")
    public Result<List<CourseType>> getCourseTypeList(){
        List<CourseType> typeList = courseService.getCourseTypeList();
        return Result.ok(typeList);
    }

    // 获取标签类型列表
    @GetMapping("/tagTypeList")
    public Result<List<TagType>> getTagList(){
        List<TagType> tagList = courseService.getTagList();
        return Result.ok(tagList);
    }

    // 获取课程信息
    @GetMapping("/courseInfo")
    public Result<CourseVo> getCourseInfo(String courseId){
        if(StringUtils.isNullOrEmpty(courseId)){
            return Result.error(500,"课程ID不能为空");
        }

        CourseVo course = courseService.getCourseVo(courseId);
        return course!=null ? Result.ok(course) : Result.error(500,"获取课程信息失败");
    }

    // 创建新课程
    @PostMapping("/addCourse")
    public Result<String> addCourse(@RequestBody Course course){
        if (StringUtils.isNullOrEmpty(course.getClstype())) {
            return Result.error(400,"课程类型不能为空");
        }
        Boolean flag = courseService.addCourse(course);
        if(flag){
            return Result.ok("添加课程成功");
        }
        return Result.error(500,"添加课程失败，请重试");
    }

    // 修改课程信息
    @PostMapping("/updateCourse")
    public Result<String> updateCourse(@RequestBody Course course){
        Boolean flag = courseService.updateCourse(course);
        return flag ? Result.ok("修改课程信息成功") : Result.error(500,"修改课程信息失败，请检查权限信息");
    }

    // 根据课程名称进行模糊查询
    @GetMapping("/search")
    public PageResult<CourseVo> getCourseBySearch(String courseName,Integer current,Integer size) throws ExecutionException, InterruptedException, TimeoutException {
        if(size==null){
            size = 10;
        }
        if(current==null){
            current  = 1;
        }
        current = (current-1) * size;
        if(!StringUtils.isNullOrEmpty(courseName)){
            courseName = "%"+courseName + "%";
        }
        return courseService.getCourseBySearch(courseName,current,size);
    }

    // 获取课程分类信息
    @GetMapping("/getCourseByCond")
    public PageResult<CourseVo> getCourseListByCond(String tagCode, String typeCode, Integer current, Integer size) throws ExecutionException, InterruptedException, TimeoutException {
        if(size==null){
            size = 10;
        }
        if(current==null){
            current  = 1;
        }
        current = (current-1) * size;
        return courseService.getCourseByCond(tagCode, typeCode, current, size);
    }

    // 获取课程信息
    @GetMapping("/courseList")
    public PageResult<Course> getCourseList(String userId, Integer current, Integer size) throws ExecutionException, InterruptedException {
        if(size==null){
            size = 10;
        }
        if(current==null){
            current = 1;
        }
        current = (current-1) * size;
        return courseService.getCourseList(userId,current,size);
    }

    // 删除课程信息
    @PostMapping("/delCourse")
    public Result<String> delCourse(String courseId) throws ExecutionException, InterruptedException, TimeoutException {
        Boolean flag = courseService.delCourse(courseId);
        return flag ? Result.ok("删除课程信息成功") : Result.error(500,"删除课程信息失败，请检查权限信息");
    }

    // 删除课程章节
    @PostMapping("/delChapter")
    public Result<String> delChapter(String courseId,String chapterId) throws ExecutionException, InterruptedException, TimeoutException {
        Boolean flag = chapterService.delChapter(courseId,chapterId);
        return flag ? Result.ok("删除课程章节成功") : Result.error(500,"删除课程章节失败，请检查权限信息");
    }

    // 添加课程章节
    @PostMapping("/addChapter")
    public Result<String> addChapterInfo(@RequestBody Chapter chapter){
        String courseId = chapter.getCourseid();
        if (StringUtils.isNullOrEmpty(courseId)) {
            return Result.error(500,"课程ID不能为空");
        }
        Course course = courseService.getById(courseId);
        if(course==null){
            return Result.error(500,"课程信息不存在");
        }

        Boolean flag = chapterService.addChapterInfo(chapter);
        return flag ? Result.ok("添加课程成功") : Result.error(500,"添加课程失败,请重试");
    }

    // 添加章节视频
    @PostMapping("/addChapter/video")
    public Result<String> addChapterVideo(@RequestParam("videoId") String videoId,@RequestParam("chapterId") String chapterId,
                      @RequestParam("title") String title,@RequestParam("duration") String duration,@RequestParam("courseId") String courseId){
        ChapterVideo chapterVideo = new ChapterVideo();
        chapterVideo.setVideoid(videoId);
        chapterVideo.setChapterid(chapterId);
        chapterVideo.setTitle(title);
        chapterVideo.setDuration(duration);
        chapterVideo.setIslive(false);

        Boolean flag = courseService.addChapterVideo(chapterVideo,courseId);
        return flag ? Result.ok("添加章节视频成功") : Result.error(500,"添加章节视频失败,请重试");
    }

    // 获取课程下的章节信息
    @GetMapping("/getCosChapter")
    public Result<List<ChapterVo>> getCosChapterList(String courseId) throws ExecutionException, InterruptedException {
        User user = UserContextHolder.get();
        liveRoomService.updateLearnCount(stringRedisTemplate, userMapper,user);
        return Result.ok(chapterService.getChapterByCourseId(courseId));
    }

    // 删除课程下的章节信息
    @GetMapping("/delCosChapter")
    public Result<String> delCosChapter(String chapterId) throws ExecutionException, InterruptedException, TimeoutException {
        if (StringUtils.isNullOrEmpty(chapterId)) {
            return Result.error(500,"删除章节信息失败");
        }
        // 判断章节是否存在
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("ChapterID",chapterId);
        if (!chapterService.exists(wrapper)) {
            return Result.error(500,"要删除的章节信息不存在");
        }
        Boolean flag = chapterService.delCosChapter(chapterId);
        return flag ? Result.ok("删除章节信息成功") : Result.error(500,"删除课程信息失败");
    }

    // 用户加入课程
    @GetMapping("/joinCourse")
    public Result<String> joinCourse(String courseId){
        Course course = courseService.getById(courseId);
        if(course==null){
            return Result.error(500,"课程信息不存在，请检查后重试");
        }
        // 判断用户是否已经加入了该课程
        String userid = UserContextHolder.get().getUserid();
        Boolean flag = courseService.joinCourse(userid,courseId);
        return flag ? Result.ok("加入课程成功"):Result.error(500,"加入课程失败,请检查是否已加入课程");
    }

    // 热门课程
    @GetMapping("/hotCourse")
    public Result<List<CourseVo>> getHot(){
        List<CourseVo> courseList = courseService.getHot();
        return Result.ok(courseList);
    }

    // 点赞数+1
    @GetMapping("/likeAdd")
    public Result<Void> likeAdd(String courseId){
        chapterService.updateLikeCount(courseId);
        return Result.ok();
    }

    // 返回章节视频地址
    @GetMapping("/videoSource")
    public Result<SystemFile> getVideoSource(String fileId){
        SystemFile video = fileService.getVideoById(fileId);
        if(video!=null){
            return Result.ok(video);
        }else{
            return Result.error(500,"获取视频失败");
        }
    }

    // 教师查询自己发布的课程
    @GetMapping("/getOwnCourse")
    public Result<List<CourseVo>> getOwnCourse(){
        User user = UserContextHolder.get();

        List<CourseVo> courses = courseService.getOwnCourse(user.getUserid());
        return Result.ok(courses);
    }

    //获取课程用户发布的课程Id以及名称
    @GetMapping("/getOwnCourseNameList")
    public Result<List<Course>> getOwnCourseNameList(){
        User user = UserContextHolder.get();
        List<Course> list = courseService.getOwnCourseNameList(user.getUserid());
        return Result.ok(list);
    }

    // 用户查询自己学习的课程
    @GetMapping("/getMyLearn")
    public Result<List<CourseVo>> getMyLearn(){
        List<CourseVo> courseVos = courseService.getMyLearn();
        return Result.ok(courseVos);
    }

    @GetMapping("/topClickTag")
    public Result<List<TagVo>> getTopTag() throws ExecutionException, InterruptedException {
        List<TagVo> list = tagTypeService.getTopTag();
        return Result.ok(list);
    }

    @GetMapping("/topCourse")
    public Result<List<Course>> getTop5(){
        return Result.ok(courseService.getTop5());
    }
}
